# coding:utf-8
import datetime

from selenium import webdriver
import time
import random
import uuid
from selenium.webdriver import ActionChains

import os, re, io

import numpy as np
import requests
import sys
import traceback, base64
import json, urllib
import hashlib
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import PyChromeDevTools
from selenium.webdriver.support.select import Select

from selenium.webdriver.common.keys import Keys

from bs4 import BeautifulSoup


def Email(port):
    try:
        options = webdriver.ChromeOptions()
        print("开始加载浏览器配置")

        d = DesiredCapabilities.CHROME
        d['loggingPrefs'] = {'performance': 'ALL'}
        options.add_experimental_option("debuggerAddress", "127.0.0.1:" + port)

        browser = webdriver.Chrome(chrome_options=options, desired_capabilities=d)
        chrome = PyChromeDevTools.ChromeInterface(host="127.0.0.1", port=int(port))

        chrome.Network.enable()
        chrome.Page.enable()

        time.sleep(10)
        shifouyishangchuan = 0
        if not browser.find_element_by_xpath('//*[@id="paginaCentral"]'):
            print('未找到元素')
            browser.quit()

            # 切换到frame中
        browser.switch_to.frame(browser.find_element_by_xpath('//*[@id="paginaCentral"]'))
        print('已切换到主frame中...')

        # 当天日期
        day_tiannn = datetime.datetime.now()
        ar=(datetime.datetime.now()+datetime.timedelta(hours=-11)).weekday()
        if ar == 5:
            day_tian = (day_tiannn + datetime.timedelta(hours=-11) + datetime.timedelta(days=+2)).strftime('%d/%m/%Y')
        elif ar == 6:
            day_tian = (day_tiannn + datetime.timedelta(hours=-11) + datetime.timedelta(days=+1)).strftime('%d/%m/%Y')
        else:
            day_tian = (day_tiannn + datetime.timedelta(hours=-11)).strftime('%d/%m/%Y')
        week_day_dict = {
            0: '星期一',
            1: '星期二',
            2: '星期三',
            3: '星期四',
            4: '星期五',
            5: '星期六',
            6: '星期天',
        }
        print(week_day_dict[datetime.datetime.now().weekday()])
        print('当天巴西日期:{}'.format(day_tian))
        #
        while True:

            try:
                if browser.find_element_by_xpath('//*[@id="extratoInicioForm"]/div[3]/div[1]/label/label'):
                    # 两天数据
                    # browser.find_element_by_xpath('//*[@id="extratoInicioForm"]/div[3]/div[1]/label/label').click()
                    # 七天数据
                    browser.find_element_by_xpath('//*[@id="extratoInicioForm"]/div[3]/div[2]/label/label').click()

                    time.sleep(10)

                    html = browser.find_element_by_xpath(
                        '//*[@id="extratoInicioForm:listagem:tbody_element"]').get_attribute("innerHTML")
                    alllist = []
                    soup = BeautifulSoup(html, features='lxml')

                    # print(soup.prettify())
                    tr_obj_list = soup.find_all("tr")
                    # print(tr_obj_list)
                    print(len(tr_obj_list))
                    click_list = []
                    date = ''
                    for ii in tr_obj_list:
                        tdlist = []
                        td_obj_list = ii.find_all(class_='campos_form')

                        if len(td_obj_list) == 7:
                            data_1 = td_obj_list[0].find_all('span')
                            if data_1[0].text.strip() and data_1[0].text.strip():
                                mon = get_moneth(data_1[1].text.strip())
                                dd = '{0}/{1}'
                                date = dd.format(data_1[0].text.strip(), mon)

                            # print(data_1)
                            # print(td_obj_list[1].find(class_='circulo-verde'))
                            name_1 = td_obj_list[2].find_all('span')
                            # print(name_1)
                            time_x = td_obj_list[3].text.strip()
                            # print(time_x)
                            money_label = td_obj_list[4].find('label')
                            #
                            id = td_obj_list[6].find('a')['id']

                            id_str = '//*[@id="{}"]'
                            click_id = id_str.format(id)
                            print(time_x)
                            print(click_id)
                            # 获取内容详细

                            # print(money_label)
                            if td_obj_list[1].find(class_='circulo-verde'):
                                click_list.append(click_id)
                                # content = get_click_content(browser, click_id)
                                # print(content)
                                # 号
                                tdlist.append(date)  # 日期
                                tdlist.append(name_1[0].text.strip())  # 姓名
                                # tdlist.append(content[2]) # 凭证id
                                # tdlist.append(content[5]) # cpf
                                tdlist.append(name_1[1].text.strip())  # 银行
                                tdlist.append(time_x)  # 时间
                                tdlist.append(money_label.text.strip())  # 金额
                                alllist.append("|".join(tdlist))
                                # print(alllist)

                    print(alllist)

                    for ll in click_list:
                        browser.find_element_by_xpath(ll).click()
                        time.sleep(4)
                        handle = browser.current_window_handle  #
                        browser.switch_to.window(handle)  # 转到当前弹出窗口
                        browser.switch_to.frame(browser.find_element_by_xpath('//*[@id="modal_infra_estrutura"]'))
                        print('已切换到弹窗frame中')
                        # 获取弹窗内容
                        html = browser.find_element_by_xpath('//*[@id="frmDetalhes"]').get_attribute(
                            "innerHTML")
                        soup = BeautifulSoup(html, features='lxml')
                        content = soup.find_all(class_="HtmlOutputLabelBradesco")
                        ar = []
                        for c in content:
                            ar.append(c.text.strip())

                        # 关闭弹窗

                        browser.find_element_by_xpath('//*[@id="frmDetalhes:_id94"]').click()

                        browser.switch_to.default_content()

                        # 切出
                        browser.switch_to.parent_frame(browser.find_element_by_xpath('//*[@id="paginaCentral"]'))
                        # print('已出弹窗frame')

                        print(ar)

                    day_time = (day_tiannn + datetime.timedelta(hours=-11)).strftime('%Y-%m-%d %H:%M:%S')
                    output = """操作时间：{} \n数据：{} \n"""
                    save_txt(output.format(day_time, json.dumps({"all": alllist, "flag": 1})))
                    time.sleep(40)  # 刷新时间

            except Exception as e:
                print(e)

            time.sleep(3)

    except Exception as e:
        # browser.quit()
        print(traceback.print_exc())
        print(str(e))
        return False

    # browser.quit()


def get_click_content(driver, id):
    driver.find_element_by_xpath(id).click()
    time.sleep(4)
    # handle = driver.current_window_handle  #
    # driver.switch_to.window(handle)  # 转到当前弹出窗口
    # driver.switch_to.frame(driver.find_element_by_xpath('//*[@id="modal_infra_estrutura"]'))
    # print('已切换到弹窗frame中')
    # 获取弹窗内容
    html = driver.find_element_by_xpath('//*[@id="frmDetalhes"]').get_attribute(
        "innerHTML")
    soup = BeautifulSoup(html, features='lxml')
    content = soup.find_all(class_="HtmlOutputLabelBradesco")
    ar = []
    for c in content:
        ar.append(c.text.strip())

    # 关闭弹窗
    driver.find_element_by_xpath('//*[@id="frmDetalhes:_id94"]').click()
    # 切出
    # driver.switch_to.default_content()
    # print('已出弹窗frame')

    # driver.switch_to.frame(driver.find_element_by_xpath('//*[@id="paginaCentral"]'))
    # print('切换到主frame中')

    return ar


def get_moneth(str):
    arr = {'JAN': '01', 'FEV': '02', 'MAR': '03', 'ABR': '04', 'MAI': '05', 'JUN': '06', 'JUL': '07', 'AUO': '08',
           'SET': '09', 'OUT': '10', 'NOV': '11', 'DEZ': '12'}
    day_tiannn = datetime.datetime.now()
    year = (day_tiannn + datetime.timedelta(hours=-11)).strftime('%Y')
    md = '{0}/{1}'
    return md.format(arr[str], year)


# 保存到文本中
def save_txt(data):
    name = '{0}.txt'
    day_tiannn = datetime.datetime.now()
    day = (day_tiannn + datetime.timedelta(hours=-11)).strftime('%Y-%m-%d')
    with open(name.format(day), 'a', encoding='utf-8') as f:
        f.write(data)


port = ""
with open(sys.path[0].replace("\\", "/") + "/DevToolsActivePort", "r")as f:
    data = f.read()
    print(data)
    port = data.split("\n")[0]
Email(port=port)
# while True:
#     Email(port=port)
#     time.sleep(20)
